package com.example.qqviewspringboot.repository;

import com.example.qqviewspringboot.data.Friendship;
import com.example.qqviewspringboot.data.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface FriendshipRepository extends JpaRepository<Friendship, Long> {

    // 查找用户与好友之间的好友关系
    @Query("SELECT f FROM Friendship f WHERE f.user.id = :userId AND f.friend.id = :friendId")
    Optional<Friendship> findByUserAndFriend(
            @Param("userId") Long userId,
            @Param("friendId") Long friendId
    );

    @Query("SELECT f FROM Friendship f WHERE (f.userId = :userId OR f.friendId = :userId) AND f.status = 'ACCEPTED'")
    List<Friendship> findAcceptedFriendships(@Param("userId") Long userId);
    @Query("SELECT f FROM Friendship f WHERE f.friendId = :friendId AND f.status = 'PENDING'")
    List<Friendship> findPendingRequestsByFriendId(@Param("friendId") Long friendId);

    // 查找用户与好友之间的好友关系（简化版）
    Optional<Friendship> findByUserIdAndFriendId(Long userId, Long friendId);

    // 根据用户 ID 和状态查找好友关系
    List<Friendship> findByUserIdAndStatus(Long userId, Friendship.Status status);
    List<Friendship> findByFriendIdAndStatus(Long friendId, Friendship.Status status);
    @Query("SELECT f FROM Friendship f WHERE (f.userId = :userId OR f.friendId = :userId) AND f.status = :status")
    List<Friendship> findByUserIdOrFriendIdAndStatus(@Param("userId") Long userId, @Param("status") Friendship.Status status);

    List<Friendship> findByUserIdOrFriendIdAndStatus(Long userId, Long friendId, Friendship.Status status);


    @Query("SELECT u FROM User u WHERE u.id IN (SELECT f.userId FROM Friendship f WHERE f.friendId = :userId AND f.status = :status)")
    List<User> findPendingRequestSenders(@Param("userId") Long userId, @Param("status") Friendship.Status status);
    @Query("SELECT f FROM Friendship f WHERE (f.userId = :userId AND f.friendId = :friendId OR f.userId = :friendId AND f.friendId = :userId) AND f.status = 'PENDING'")
    Optional<Friendship> findPendingFriendship(@Param("userId") Long userId, @Param("friendId") Long friendId);


}


